package com.cloud.salon.gateway.bean;

import com.cloud.salon.gateway.feign.MenberFeign;
import com.cloud.salon.gateway.feign.UserFeign;
import com.cloud.salon.common.base.entity.authority.Authority;
import com.cloud.salon.common.base.entity.menber.Staff;
import com.cloud.salon.common.base.response.Res;
import com.cloud.salon.common.base.entity.authority.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


/*
 * 权限控制用户实体自定义业务
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
	Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	
//	@Autowired
//	private UserRepository userRep;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MenberFeign menberFeign;

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 获取用户
	    Res<User> userRes = userFeign.findByUsername(username);
		User user = userRes.getData();

		// 获取用户权限
        Res<List<Authority>> authorityRes = userFeign.findAuthorityByUser(user.getId());
        // 获取用户对应的员工信息
        Res<Staff> staffRes = menberFeign.findStaffByUser(user.getId());

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        return new UserDetailImpl(user, authorityRes.getData(), staffRes.getData());
	}
}
